<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;


class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, HasRoles;

    protected $guard_name = 'sanctum'; // sanctum 和 spatie/permisson有冲突，导致后者没法获取正确的guard_name, 因为后者是读取.config('auth.defaults.guard')的，而这个选项刚好不是'sanctum'

    // 添加 'dept' 到附加属性中
    protected $appends = ['group', 'roleName'];

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name', 'email', 'password', 'avatar', 'userName', 'dept'
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'created_at' => 'datetime:Y-m-d H:i:s',
        'dept' => 'array'
    ];

    public function deptId()
    {
        return $this->belongsTo(UserDept::class, 'dept');
    }

    //属于那个权限组
    public function getgroupAttribute()
    {
        // 通过角色关系获取相关的 model_has_role 表的数据
        return $this->roles()->pluck('id');
    }

    //属于那个权限组
    public function getroleNameAttribute()
    {
        // 通过角色关系获取相关的 model_has_role 表的数据
        return $this->roles()->pluck('label');
    }
}
